package View;

import java.awt.Image;
import java.awt.image.PixelGrabber;


import javax.swing.ImageIcon;

import javax.swing.JToggleButton;


public class OsterEiButton extends JToggleButton {

	private int imageWidth;
	private int[] imagePixel;
	private int backgroundRed;
	private int backgroundGreen;
	private int backgroundBlue;
	private ImageIcon icon;
	

	public OsterEiButton(ImageIcon icon) {
		this.icon=icon;
		this.setIcon(icon);
		this.imagePixel=calculatePixel();
	}

	public boolean contains(int posX, int posY) {
		int red, green, blue;
		int colorValue;
		if (super.contains(posX, posY)) {
			if (imagePixel == null)
				imagePixel = this.calculatePixel();
			colorValue = imagePixel[posX + imageWidth * posY];
			red = (colorValue & 0x00ff0000) >> 16;
			green = (colorValue & 0x0000ff00) >> 8;
			blue = colorValue & 0x000000ff;
			return !(red == backgroundRed && green == backgroundGreen && blue == backgroundBlue);
		} else
			return false;
	}

	private int[] calculatePixel() {
		int colorValue;
		
		Image image = ((ImageIcon)this.getIcon()).getImage();
		
		int[] pixel = new int[image.getWidth(this) * image.getHeight(this)];
		PixelGrabber pg = new PixelGrabber(image, 0, 0, image.getWidth(this),
				image.getHeight(this), pixel, 0, image.getWidth(this));
		try {

			pg.grabPixels();
			colorValue = pixel[0];
			backgroundRed = (colorValue & 0x00ff0000) >> 16;
			backgroundGreen = (colorValue & 0x0000ff00) >> 8;
			backgroundBlue = colorValue & 0x000000ff;
		} catch (InterruptedException e) {
		}
		return pixel;

	}

}
